﻿using UnityEditor;
using UnityEditor.Build;
using UnityEditor.Build.Reporting;
using UnityEngine;
using System.IO;

namespace HKTools
{
    public class HK_BuildInfoGenerator : IPreprocessBuildWithReport
    {
        public int callbackOrder => 0;

        public void OnPreprocessBuild(BuildReport report)
        {
            // 创建配置信息
            BuildInfo info = new BuildInfo
            {
                companyName = PlayerSettings.companyName,
                productName = PlayerSettings.productName,
                version = PlayerSettings.bundleVersion,
                buildTime = System.DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"),
                platform = report.summary.platform.ToString(),
                customInfo = HK_BuildInfoEditorWindow.GetCustomBuildInfo()
            };

            // 序列化配置信息为JSON
            string json = JsonUtility.ToJson(info, true);

            // 确保Resources文件夹存在
            string resourcesPath = Application.dataPath + "/Resources";
            if (!Directory.Exists(resourcesPath))
            {
                Directory.CreateDirectory(resourcesPath);
            }

            // 保存配置文件
            string filePath = resourcesPath + "/BuildInfo.json";
            File.WriteAllText(filePath, json);

            // 刷新AssetDatabase
            AssetDatabase.Refresh();
        }

        // 获取自定义构建信息
        // string GetCustomBuildInfo()
        // {
        //     // 尝试获取编辑器窗口中设置的自定义信息
        //     try
        //     {
        //         // 使用反射调用Editor命名空间中的方法，避免运行时依赖
        //         var editorWindowType = System.Type.GetType("HKTools.HK_BuildInfoEditorWindow, Assembly-CSharp-Editor");
        //         if (editorWindowType != null)
        //         {
        //             var method = editorWindowType.GetMethod("GetCustomBuildInfo", System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Static);
        //             if (method != null)
        //             {
        //                 return method.Invoke(null, null) as string;
        //             }
        //         }
        //     }
        //     catch (System.Exception e)
        //     {
        //         Debug.LogWarning("Failed to get custom build info: " + e.Message);
        //     }

        //     // 如果反射调用失败，直接从EditorPrefs获取
        //     return EditorPrefs.GetString("HK_BuildInfo_CustomInfo", "");
        // }
    }
}